package com.project.springboot.mongodb.templates.repository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import com.mongodb.client.result.UpdateResult;
import com.project.springboot.mongodb.templates.domain.User;

@Service
public class UserRepositoryImpl implements UserRepository {

	@Autowired
	private MongoTemplate mongoTemplate;
	
	@Override
	public void save(User user) {
		mongoTemplate.save(user);
	}

	@Override
	public User findByUserName(String userName) {
		Query query = new Query(Criteria.where("userName").is(userName));
		return mongoTemplate.findOne(query, User.class);
	}

	@Override
	public long update(User user) {
		Query query = new Query(Criteria.where("id").is(user.getId()));
		Update update = new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord());
		
		UpdateResult result = mongoTemplate.updateFirst(query, update, User.class);
		
		if (result != null) {
			return result.getMatchedCount();
		}
		return 0;
	}

	@Override
	public void deleteById(Long id) {
		Query query = new Query(Criteria.where("id").is(id));
		mongoTemplate.remove(query, User.class);
	}

}
